/*
 * Copyright (c) 2011. c.mueller
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * The Software shall be used for Good, not Evil.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package de.altitude.cimuelle;

import de.altitude.cimuelle.utils.ServerOperations;
import org.apache.log4j.Logger;

import javax.naming.ConfigurationException;

/**
 * User: cybernaut
 * Date: 23.07.11
 * Time: 13:42
 */
public class MessageTask {
    private Config prop;

    private static MessageTask instance;
    private static ThreadGroup tg;

    private final Logger logger = Logger.getLogger("MessageTask");

    private MessageTask() {
        tg = new ThreadGroup("MessageTask");
        prop = Config.getInstance();
    }

    public static synchronized MessageTask getInstance() {
        if (MessageTask.instance == null) {
            MessageTask.instance = new MessageTask();
        }
        return MessageTask.instance;
    }

    public synchronized void startMessageTask(String port2) {
        final String port = port2;
        if (isTaskStarted(port)) {
            logger.info(port + " has been started already.");
            return;
        }
        new Thread(tg, port) {
            @Override
            public void run() {
                logger.info(port + " Thread started.");
                while (true) {
                    try {
                        int timer = Integer.parseInt(prop.getConfig(port + ".timerMessageIntervall", prop.getConfig("timerMessageInvervall", "0")));
                        if (timer <= 0) {
                            throw new InterruptedException();
                        }
                        sleep(timer * 1000);
                        try {
                            String command = port + ",console,serverMessage " + prop.getConfig(port + ".timerMessage", prop.getConfig("timerMessage", ""));
                            ServerOperations.sendSingleCommand(command);
                        } catch (ConfigurationException e) {
                            e.printStackTrace();
                        }
                    } catch (InterruptedException e) {
                        logger.info(port + " Thread stopped.");
                        break;
                    }
                }
            }
        }.start();
    }

    private synchronized boolean isTaskStarted(String port) {
        Thread[] list = new Thread[tg.activeCount()];
        tg.enumerate(list);
        for (Thread aList : list) {
            if (port.equals(aList.getName())) {
                return true;
            }
        }
        return false;
    }

    public synchronized void stopTasks() {
        Thread[] list = new Thread[tg.activeCount()];
        tg.enumerate(list);
        for (Thread aList : list) {
            if (aList == null) {
                continue;
            }
            aList.interrupt();
            try {
                aList.join(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
